package com.jbh.recordlibrary.v;

import android.content.Context;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import com.google.gson.Gson;
import com.jbh.recordlibrary.R;
import com.jbh.recordlibrary.f.cheap.CheapWAVByTime;
import com.jbh.recordlibrary.i.AddAudioRecordListener;
import com.jbh.recordlibrary.i.CallBack;
import com.jbh.recordlibrary.u.LogUtil;
import com.jbh.recordlibrary.u.SdcardUtil;
import java.io.File;
import java.util.List;


public class RecordWaveCutView extends LinearLayout implements View.OnTouchListener {

    private View view ;
    private RecordTimeView mRecordTimeView ;
    private RecordWaveView mRecordWaveView;
    private ImageView im_offest_left , im_offest_right;
    private View cutVoiceView ;
    private float totalLength ;
    private float oneSecondLength;
    private float divider;
    private List<Short> totalBuf;
    private String recordFilePath;
    /**截取的区间*/
    private float[] cutVal = new float[2];
    /**时间区间*/
    private float[] cutTime = new float[2];
    /**截取音频数据索引*/
    private int[] cutPosition = new int[2];


    /**
     * 拉动左边
     *
     * @param event
     */
    private float downLeftX;          // 记录上一次x坐标
    private float lastLeftDx;         // 记录上一次移动距离
    private float currentLeftDx = 0;  // 当前移动的距离
    private boolean isInterpretation = false;
    /**
     * 拉动左边
     *
     * @param event
     */
    private float downRightX;          // 记录上一次x坐标
    private float lastRightDx;         // 记录上一次移动距离
    private float currentRightDx = 0;  // 当前移动的距离


    public RecordWaveCutView(Context context) {
        this(context,null);
    }


    public RecordWaveCutView(Context context,  AttributeSet attrs) {
        this(context, attrs,0);
    }



    public RecordWaveCutView(Context context,  AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        addView(view = LayoutInflater.from(context).inflate(R.layout.cut_record_layout,this,false));
        mRecordTimeView = view.findViewById(R.id.mRecordTimeView);
        mRecordWaveView = view.findViewById(R.id.mRecordWaveView);
        mRecordWaveView.setSupportDrawLine(false);
        im_offest_left = view.findViewById(R.id.im_offest_left);
        im_offest_left.setOnTouchListener(this);

        im_offest_right = view.findViewById(R.id.im_offest_right);
        im_offest_right.setOnTouchListener(this);

        cutVoiceView = view.findViewById(R.id.cutVoiceView);
    }







    /**
     * @param divider
     * @param oneSecondLength
     * @param totalBuf
     * @param totalTime
     * @param totalLength
     * @param recordFilePath
     */
    public void setRecordData(float divider,
                            float oneSecondLength,
                            List<Short> totalBuf,
                            final long totalTime,
                            float totalLength,
                            String recordFilePath) {

        this.divider = divider ;
        this.totalBuf=totalBuf;
        this.totalLength = totalLength + 2;
        this.oneSecondLength = oneSecondLength ;
        this.recordFilePath=recordFilePath;
        LogUtil.LOG_V("[totalLength] - >"+ this.totalLength);


        ViewGroup.LayoutParams params = mRecordWaveView.getLayoutParams();
        params.width = (int) totalLength;
        mRecordWaveView.setLayoutParams(params);
        mRecordWaveView.setData(divider,totalBuf);
        mRecordTimeView.setData(oneSecondLength,totalTime);

        reset();
    }




    /**
     * 重置
     */
    public void reset(){
        im_offest_left.setTranslationX(0);
        im_offest_right.setTranslationX(0);
        lastLeftDx = 0 ;
        lastRightDx = 0 ;
        cutVoiceView.setTranslationX(0);
        /*调整大小*/
        measureCutVoiceView((int) (totalLength));
        /*截取区间大小*/
        cutSizeRangeVal(0, totalLength);
    }






    @Override
    public boolean onTouch(View v, MotionEvent event) {
        int id = v.getId();
        if (id == R.id.im_offest_left) {
            offestLeft(event);
        } else if (id == R.id.im_offest_right) {
            offestRight(event);
        }
        return isInterpretation;
    }






    /**
     * 左边拉动
     *
     * @param event
     */
    private void offestLeft(MotionEvent event) {
        switch (event.getAction()){
            case MotionEvent.ACTION_DOWN:
                im_offest_left.getParent().requestDisallowInterceptTouchEvent(true);
                isInterpretation=true;
                downLeftX = event.getRawX();
                break;
            case MotionEvent.ACTION_MOVE:
                /*当前手势移动距离*/
                currentLeftDx = event.getRawX() - downLeftX + lastLeftDx;
                LogUtil.LOG_V("[currentLeftDx] - > "+currentLeftDx);


                /*左边界*/
                if (currentLeftDx<0){
                    currentLeftDx = 0 ;
                }

                /*有边界*/
                if (currentLeftDx>totalLength) {
                    currentLeftDx = totalLength ;
                }

                float temp =  totalLength - currentLeftDx + lastRightDx ;
                if (temp <= fiveSecondWidth()){
                    currentLeftDx = lastLeftDx = totalLength - fiveSecondWidth() + lastRightDx ;
                    im_offest_left.setTranslationX(currentLeftDx);
                    cutVoiceView.setTranslationX(currentLeftDx);
                    measureCutVoiceView((int) fiveSecondWidth());
                }else {
                    im_offest_left.setTranslationX(currentLeftDx);
                    cutVoiceView.setTranslationX(currentLeftDx);
                    measureCutVoiceView((int) (totalLength - currentLeftDx + lastRightDx));
                }
                break;
            case MotionEvent.ACTION_UP:
            case MotionEvent.ACTION_CANCEL:
                lastLeftDx = currentLeftDx;
                cutSizeRangeVal(lastLeftDx,totalLength + lastRightDx);
                isInterpretation=false;
                im_offest_left.getParent().requestDisallowInterceptTouchEvent(false);
                break;
        }
    }




    private void offestRight(MotionEvent event) {
        switch (event.getAction()){
            case MotionEvent.ACTION_DOWN:
                im_offest_right.getParent().requestDisallowInterceptTouchEvent(true);
                isInterpretation=true;
                downRightX =  event.getRawX();
                break;
            case MotionEvent.ACTION_MOVE:
                /*当前移动距离*/
                currentRightDx =  event.getRawX()  - downRightX    + lastRightDx;
                /*右边界*/
                if (currentRightDx>0){
                    currentRightDx = 0 ;
                }

                float temp  = (totalLength + currentRightDx - lastLeftDx) ;
                if (temp <= fiveSecondWidth()){
                    currentRightDx = lastRightDx =  fiveSecondWidth() - totalLength + lastLeftDx;
                    im_offest_right.setTranslationX(currentRightDx);
                    measureCutVoiceView((int) fiveSecondWidth());
                }else {
                    im_offest_right.setTranslationX(currentRightDx);
                    measureCutVoiceView((int) temp);
                }

                break;
            case MotionEvent.ACTION_UP:
            case MotionEvent.ACTION_CANCEL:
                lastRightDx = currentRightDx;
                cutSizeRangeVal(lastLeftDx,totalLength + lastRightDx);
                isInterpretation=false;
                im_offest_right.getParent().requestDisallowInterceptTouchEvent(false);
                break;
        }
    }



    /**
     * 区间大小
     *
     * @param dx
     * @param dx1
     */
    private void cutSizeRangeVal(float dx, float dx1) {
        cutVal[0] = dx ;
        cutVal[1] = dx1 ;
        LogUtil.LOG_V("[cutVal] - > "+new Gson().toJson(cutVal));
        rangeTime();
        rangePosition();

        if (addAudioRecordListener!=null){
            addAudioRecordListener.onCutRecord(divider,oneSecondLength,cutTotalLength(),getBuf(),getTime());
        }
    }



    /**
     * 获取截取之后的总长度
     *
     * @return
     */
    private float cutTotalLength() {
        return cutVal[1] - cutVal[0];
    }




    /**
     * 获取截取后的文件时长
     *
     * @return
     */
    private float getTime() {
        return  cutTime[1] - cutTime[0];
    }





    /**
     * 获取截取后的数据
     *
     * @return
     */
    private List<Short> getBuf() {
        if (totalBuf!=null&&totalBuf.size()>0){
            try {
                if (cutPosition[1]>totalBuf.size()){
                    cutPosition[1] = totalBuf.size();
                }
                return totalBuf.subList(cutPosition[0],cutPosition[1]);
            }catch (IndexOutOfBoundsException e){
                e.printStackTrace();
            }
        }
        return null ;
    }




    /**
     * 区间时间
     */
    private void rangeTime(){
        float start = cutVal[0];
        float end = cutVal[1];
        cutTime [0] = (float) (start*1.0 / oneSecondLength);
        cutTime [1] = (float) (end*1.0 / oneSecondLength);
        LogUtil.LOG_V("[cutTime] - > "+new Gson().toJson(cutTime));
    }





    /**
     * 音波数据截取的索引
     */
    private void rangePosition(){
        float start = cutVal[0];
        float end = cutVal[1];
        cutPosition[0] = (int) (start  * 1.0 / divider);
        cutPosition[1] = (int) Math.ceil( end  * 1.0 / divider);
        LogUtil.LOG_V("[cutPosition] - > "+new Gson().toJson(cutPosition));
    }



    /**
     * 5秒的长度
     *
     * @return
     */
    private float fiveSecondWidth() {
        return oneSecondLength * 5 ;
    }



    /**
     * 改变显示截取区域
     *
     * @param w
     */
    private void measureCutVoiceView(int w) {
        ViewGroup.LayoutParams param = cutVoiceView.getLayoutParams();
        param.width = w;
        cutVoiceView.setLayoutParams(param);
    }



    private AddAudioRecordListener addAudioRecordListener ;


    public void setAddAudioRecordListener(AddAudioRecordListener addAudioRecordListener) {
        this.addAudioRecordListener = addAudioRecordListener;
    }



    /**
     * 截取文件
     *
     * @param callBack
     */
    public void cutFileTask(final CallBack<String> callBack){
        /*创建存放剪切文件夹*/
        String path = SdcardUtil.getSaveDir(getContext())+File.separator+"cut_files";
        File cutFile=new File(path);
        if(!cutFile.exists()){
            cutFile.mkdirs();
        }

        /*输出文件路径*/
        File outputFile = new File(cutFile.getAbsolutePath() ,"cut_"+System.currentTimeMillis()+".wav");
        /*开始剪切文件*/
        CheapWAVByTime.cutWavFile(recordFilePath, outputFile.getAbsolutePath(),
                (int) (cutTime[0] * 1000),
                (int) Math.ceil(cutTime[1] * 1000), new CallBack<String>() {
                    @Override
                    public void success(String s) {
                        if (callBack!=null){
                            callBack.success(s);
                        }
                    }
                    @Override
                    public void error(String error) {
                        if (callBack!=null){
                            callBack.success(error);
                        }
                    }
                });
    }
}
